package com.wnzt.baszh.util.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.xml.security.utils.Base64;

public class ExtractorCJKPDF {
	/**
	 * @param args
	 */
	public static void pdf2text(String pdffile, String txtfile)
			throws IOException {

		String pdfname = pdffile;
		String txtname = txtfile;
		String xpdfpath = "D:\\xpdf\\";
		String[] cmd = new String[] { xpdfpath + "pdftotext", "-layout",
				"-enc", "UTF-8", "-nopgbrk", pdfname, txtname };
		// -layout表示保持原有的layout，enc指定字符集，-nopgbrk指定不分页
		Process p = Runtime.getRuntime().exec(cmd);
		//d:\xpdf>pdftotext.exe  -enc GBK d:/xpdf/pdf/病程记录.pdf d:/xpdf/txt/病程记录.tx
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			List<File> filelist=new ArrayList<File>();
			filelist=PdfParser.getFileList(filelist,"E:\\pdf2");
			for (File file : filelist) {
				String txtfile="D:/pdftotxt/"+file.getName().substring(0,file.getName().lastIndexOf("."))+".txt";
				FileUtil.createFile(txtfile);
				pdf2text(file.getPath(),txtfile);
				String content=convertInputSteamToString(txtfile);
				Pattern p = Pattern.compile("\\s+");
	            Matcher m = p.matcher(content);
	            content= m.replaceAll("");//变成一行字符串
	            content=content.replaceAll("：", "");
	            content=content.replaceAll(":", "");
	            String zyid=null;
	            System.out.println(txtfile);
	            if(content.indexOf("住院号")!=-1){
	            	System.out.println(txtfile);
	            	zyid=content.substring(content.indexOf("住院号")+3,content.indexOf("住院号")+9);
	            	System.out.println(zyid);
	            }
	            //D:/pdftotxt/病案首页.txt
	            //D:/pdftotxt/病案首页续页.txt
	            //D:/pdftotxt/长期医嘱单.txt
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static String convertInputSteamToString(String filepath) throws FileNotFoundException {
		InputStream inputStream=new FileInputStream(new File(filepath));
	    BufferedReader reader = new BufferedReader(new InputStreamReader(
	            inputStream));
	    StringBuilder stringBuilder = new StringBuilder();
	 
	    try {
	        for (String line = reader.readLine(); line != null; line = reader
	                .readLine()) {
	            stringBuilder.append(line + "\n");
	        }
	        inputStream.close();
	        return stringBuilder.toString();
	    } catch (IOException e) {
	        throw new RuntimeException(e);
	    }
	}
}
